package qj.tool.gae;

import java.util.*;

import qj.tool.gae.db.Unindexed;
import qj.util.funct.P1;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Text;

/**
 * @author Le Anh Quan
 *
 */
public class Log {
	public Long id;
	public Date time;
	public String level;
	@Unindexed
	public String message;
	
	public static boolean sysoutLog = false;
	
	public static Map<String,P1<String>> logListeners = new HashMap<String, P1<String>>();

	public static void addListener(String level, P1<String> p) {
		logListeners.put(level, p);
	}
	
	public static void critical(String message) {
		log("critical",message);
	}
	public static void error(String message) {
		log("error",message);
	}
	public static P1<String> errorF = new P1<String>() {public void e(String obj) {
		error(obj);
	}};
	
	public static void warn(String message) {
		log("warn",message);
	}
	public static void info(String message) {
		log("info",message);
	}
	public static void debug(String message) {
		if (sysoutLog) {
			// log("debug",message);
			System.out.println(message);
		}
	}

	private static void log(String level, String message) {
		Entity entity = new Entity(DB.entityType(Log.class));
		entity.setProperty("time", new Date());
		entity.setProperty("level", level);
		entity.setUnindexedProperty("message", new Text(message));
		DB.ads.put(entity);
		
		if (sysoutLog) {
			System.out.println(level + " - " + message);
		}
		
		P1<String> listener = logListeners.get(level);
		if (listener!=null) {
			listener.e(message);
		}
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time = time;
	}
	public String getLevel() {
		return level;
	}
	public void setLevel(String level) {
		this.level = level;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}
